# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2023/11/26
desc: 
sample: 
"""
import logging
import os
import random
import time

import gevent
import pymysql
from locust import FastHttpUser, task
import os
import random

from locust import HttpUser, constant, between, task, FastHttpUser, events

#class LoginTest(HttpUser): 普通进程
from locust.runners import STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP, WorkerRunner

from EmailUtils import EmailUtils
from utils import getExcelList, getExcelDict


def getDb():
    connection = pymysql.connect(host='192.168.79.170',
                                 port=3307,
                                 user='root',
                                 password='123456',
                                 db='exam_db')
    cursor = connection.cursor()
    cursor.execute("SELECT name,password FROM student")
    rows = cursor.fetchall()
    connection.close()
    return rows

is_quitting = False
#指标不满足自动停止
def sendEmail(title, msg):
    emailUtils = EmailUtils()
    # 发送一封邮件
    emailUtils.send(title=title, Context=msg, to_addrs="279313259@qq.com")


def checker(environment, **kw):
    global is_quitting
    while not environment.runner.state in [STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP]:
        print("checker-----",environment.runner.stats.total.fail_ratio,
              environment.stats.total.avg_response_time,environment.stats.total.get_response_time_percentile(0.95))
        time.sleep(1) #需要等待系统启动注册
        if environment.runner.stats.total.fail_ratio > 0.01:
            logging.error("Test failed due to failure ratio > 1%")
            is_quitting = True
        elif environment.stats.total.avg_response_time > 500:
            logging.error(f"Test failed due to average response time ratio > 500ms,quitting")
            is_quitting = True
        elif environment.stats.total.get_response_time_percentile(0.95) > 500:
            logging.error(f"Test failed due to 95th percentile response time > 500, quitting")
            is_quitting = True

        if is_quitting:
            error_msg={}
            error_msg['错误率']= environment.runner.stats.total.fail_ratio
            error_msg['平均响应时间'] = str(int(environment.stats.total.avg_response_time))+"ms"
            error_msg['top95'] = str(int(environment.stats.total.get_response_time_percentile(95)))+"ms"
            print(error_msg)
            sendEmail(title='登陆压测指标不满足需求', msg="当前指标："+ error_msg.__str__())
            environment.runner.quit()
            return

#主节点监控
# @events.init.add_listener
# def on_locust_init(environment, runner, **_kwargs):
#     if not isinstance(environment.runner, WorkerRunner):
#         gevent.spawn(checker, environment)

class exam_login(FastHttpUser): #协程
    host ='http://192.168.79.170:8085/exam/'
    usr_list =getDb()

    @task
    def login(self):
        url = '/home/login'
        params = random.choice(self.usr_list)
        print(params)
        # 随机
        data = {"name": params[0], 'password': params[1]}
        with self.client.post(url=url, data=data, catch_response=True) as response:
            json = response.json()
            if json.get('type') == 'success':
                response.success()
            else:
                response.failure(json)


if __name__ == '__main__':
    os.system('locust -f exam_login_locust.py --web-port 8091  -u 200 -r 10 -t 3h30m')